package org.jgs1904.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jgs1904.entity.Comment;
import org.jgs1904.entity.User;
import org.jgs1904.service.CommentService;
import org.jgs1904.service.impl.CommentServiceImpl;

/**
 * 	评论控制器
 * @author junki
 * @date 2020年3月26日
 */
@WebServlet("/comment")
public class CommentController extends DispatcherController {
	
	private static final long serialVersionUID = 1L;
	
	private CommentService commentService = new CommentServiceImpl();

	public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Comment comment = new Comment();
		
		try {
			BeanUtils.populate(comment, request.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e1) {
			e1.printStackTrace();
		}
		
		User onlineUser = (User)request.getSession().getAttribute("onlineUser");
		
		comment.setUser_id(onlineUser.getId());
		
		if (StringUtils.isBlank(comment.getContent())) {
			request.setAttribute("message", "评论不能为空！");
			request.getRequestDispatcher("/post?method=get&id=" + comment.getPost_id()).forward(request, response);
			return;
		}
		
		comment.setCreate_time(new Date());
		
		Comment result = null;
		try {
			result = commentService.add(comment);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		if (result == null) {
			request.setAttribute("message", "评论失败！请重试！");
			request.setAttribute("comment", comment);
			request.getRequestDispatcher("/post?method=get&id=" + comment.getPost_id()).forward(request, response);
			return;
		} else {
			request.setAttribute("message", "评论成功！");
			request.getRequestDispatcher("/post?method=get&id=" + comment.getPost_id()).forward(request, response);
			return;
		}
		
	}

}
